<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport"
	      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Document</title>
	<style>
		ul,li{
			list-style: none;

		}
		li{
			padding:10px 0;
			border-bottom: 1px solid #e0e0e0;
			min-height:60px;
		}
		.mine{
			background: #f5f5f5;

		}
	</style>
</head>
<body>
用户 <input type="text" id="user"/><br>
密码 <input type="password" id="pass"/><br>
<input type="button" id="btn1" value="注册"/><br>
<input type="button" id="btn2" value="登录"/><br>
<hr>
<textarea rows="4" cols="80" id="tet1"></textarea>
<input type="button" value="发送留言" id="btn_send"><br>
<ul id="oUl">
	<!--<li>
		<h4>张三</h4>
		<p>sfd;la;ljfadsl;jafdsl;kadfs;kljafds</p>
	</li>-->
</ul>
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
let sock = io.connect('ws://localhost:8080');
window.onload = function () {
	let cur_username = '';
	let oBtn1 = document.getElementById('btn1');
	let oBtn2 = document.getElementById('btn2');
	let oBtnSend = document.getElementById('btn_send');
	let oUser = document.getElementById('user');
	let oPass = document.getElementById('pass');
	let oTxt = document.getElementById('tet1');
	let oUl = document.getElementById('oUl');

	//注册
	oBtn1.onclick=function () {
		sock.emit('reg', oUser.value, oPass.value);
	}
	sock.on('reg_ret', (code,msg) => {
		if(code){
			alert('有错'+msg);
		}else{
			alert('成功11：'+msg);
		}
	});

	//登录
    sock.on('login_ret',(code,msg)=>{
		if(code){
			alert('登陆有错'+msg)
		}else{
			alert(msg)
			cur_username=oUser.value;
		}
    });
	oBtn2.onclick=function () {
		sock.emit('login', oUser.value, oPass.value);
	}

	//消息
    sock.on('msg_ret',(code,msg)=>{
		if(code){
			alert('消息发送失败'+msg);
		}else{
			let oLi = document.createElement('li');
				oLi.className = "mine";
				oLi.innerHTML = `<h4>${cur_username}</h4><p>${oTxt.value}</p>`;
			oUl.appendChild(oLi);
			oTxt.value='';
		}
    });
	sock.on('msg',(name,txt)=>{
		let oLi = document.createElement('li');
		oLi.innerHTML = `<h4>${name}</h4><p>${txt}</p>`;
		oUl.appendChild(oLi);
	});
	oBtnSend.onclick=function () {
		sock.emit('msg',oTxt.value);
	}
}
</script>
</body>
</html>